<template>
  <div class="home flex-v">
    <div class="header flex-h flex-hv-center">
      <div class="banner">
        <div class="logo flex-v flex-center pl-10">
          <el-image v-if="logo" :src="logo" @click="router.push('/')" />
        </div>
        <!-- <div class="title">
          <span>{{ title }}</span>
        </div> -->
      </div>

      <div class="navbar flex-h flex-hv-center">
        <p v-if="!userStore.getUser" class="ft-14 kefu mr-10">
          没有账号？请联系客服热线：200-000-200
        </p>
        <el-switch
          v-model="userStore.theme"
          class="mr-10"
          active-value="dark"
          inactive-value="light"
          @change="changeTheme"
        >
          <template #active-action>
            <i class="iconfont icon-yueliang"></i>
          </template>
          <template #inactive-action>
            <i class="iconfont icon-taiyang"></i>
          </template>
        </el-switch>
        <el-button
          v-if="userStore.getUser"
          class="liner-btn tools-btn mr-10"
          round
          @click="toolLogin"
        >
          <i class="iconfont icon-kongzhitai mr-10"></i>控制台</el-button
        >
        <el-dropdown
          :hide-on-click="true"
          class="user-info"
          trigger="click"
          @visible-change="dropDownVisibleChange"
          v-if="userStore.getUser"
        >
          <span class="el-dropdown-link">
            <el-image :src="getUserInfo.avatar" />
            <!-- <el-image src="/images/avatar/robot.jpg" /> -->
          </span>
          <template #dropdown>
            <el-dropdown-menu class="user-info-menu">
              <el-dropdown-item @click="showConfigDialog = true" disabled>
                <el-icon>
                  <UserFilled />
                </el-icon>
                <div class="ml-5">
                  <div class="username">{{ getUserInfo.nickname }} （{{ userName }}）</div>
                  <span class="ft-12 mr-10"
                    >到期时间：{{ getUserInfo.accountEndDate.join("-") }}</span
                  >
                  <span class="ft-12">剩余算力：{{ getUserInfo.computingPower }}</span>
                </div>
              </el-dropdown-item>
              <el-divider style="margin: 2px 0" />
              <el-dropdown-item
                v-if="
                  !userStore.getUser.roles.includes('gd_admin') &&
                  !userStore.getUser.roles.includes('super_admin')
                "
                @click="requestHandle('power')"
              >
                <span>申请更多算力</span>
              </el-dropdown-item>
              <el-dropdown-item
                @click="requestHandle('postpone')"
                v-if="userStore.getUser.roles.includes('company_admin')"
              >
                <span>申请账号延期</span>
              </el-dropdown-item>
              <el-divider style="margin: 2px 0" />
              <el-dropdown-item @click="logout">
                <i class="iconfont icon-logout"></i>
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <div v-else>
          <el-button class="liner-btn login-btn" @click="show = !show" round>
            <i class="iconfont icon-denglu mr-10"></i>登录</el-button
          >
          <!-- <el-button size="small" @click="router.push('/register')" round
            > <i class="icon iconfont icon-zhuce mr-10"></i>注册</el-button
          > -->
        </div>
      </div>
    </div>
    <div class="main flex-1 over-h">
      <div class="navigator hiddenScrollBar">
        <ul class="nav-items">
          <template v-for="item in mainNavs" :key="item.url">
            <li
              class="cursor flex-h flex-hv-center"
              :class="isActive(item) ? 'active' : ''"
              @click="changeNav(item)"
            >
              <i :class="{}" class="iconfont icon-aiduihua mr-10"></i>
              <span class="" :class="{}">{{ item.name }}</span>
              <div class="circle"></div>
            </li>
            <div class="line"></div>
          </template>
          <template v-if="getMenu?.menus" v-for="item in getMenu?.menus" :key="item.url">
            <h4 class="">{{ item.name }}</h4>
            <li
              class="cursor flex-h flex-hv-center"
              :class="isActive(nav) ? 'active' : ''"
              @click="changeNav(nav)"
              v-for="nav in item.children"
            >
              <i
                :class="[
                  {
                    'liner-text': isActive(nav),
                  },
                  `icon-${nav.icon}`,
                ]"
                class="iconfont mr-10"
              ></i>
              <span class="" :class="{}">{{ nav.name }}</span>
              <div class="circle"></div>
            </li>
            <div class="line"></div>
          </template>
        </ul>
      </div>

      <div class="content custom-scroll" :style="{ height: mainWinHeight + 'px' }">
        <router-view :key="routerViewKey" v-slot="{ Component }">
          <transition name="move" mode="out-in">
            <component :is="Component"></component>
          </transition>
        </router-view>
      </div>
    </div>

    <login-dialog v-model:modelValue="show" @success="loginCallback" @loginCatch="loginCatch" />
    <request-dialog ref="requestDialogRef" :phone="phone" />
    <!-- :show="show"
    @hide="store.setShowLoginDialog(false)"
    @success="loginCallback" -->
    <config-dialog :show="showConfigDialog" @hide="showConfigDialog = false" />
  </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { onMounted, ref, watch, computed, useTemplateRef } from "vue";
import { httpGet } from "@/utils/http";
import { ElMessage, ElMessageBox } from "element-plus";
import { UserFilled } from "@element-plus/icons-vue";
import { getUserToken, removeUserToken } from "@/store/session";
import LoginDialog from "@/components/LoginDialog.vue";
import { useSharedStore } from "@/store/sharedata";
import ConfigDialog from "@/components/UserInfoDialog.vue";
import RequestDialog from "@/components/RequestDialog.vue";
import { showMessageError } from "@/utils/dialog";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import { loginOut, getInfo } from "@/api/login";
const userStore = useUserStore();
let { getUserInfo, getMenu } = storeToRefs(userStore);
const router = useRouter();
const route = useRoute();
const logo = ref("http://ai.jiyundata.cn/jlntv/static/2024/12/18/logo (1).png");
const mainNavs = ref([
  {
    name: "首页",
    path: "/",
    icon: "/images/menu/app.png",
  },
  // {
  //   id: 1,
  //   name: "AI办公室",
  //   icon: "/images/menu/chat.png",
  //   url: "/chat",
  //   sort_num: 1,
  //   enabled: true,
  // },
  // {
  //   id: 2,
  //   name: "AI绘画社",
  //   icon: "/images/menu/mj.png",
  //   url: "/mj",
  //   sort_num: 2,
  //   enabled: true,
  // },
  // {
  //   id: 14,
  //   name: "AI音乐坊",
  //   icon: "/images/menu/suno.png",
  //   url: "/aiMusic",
  //   sort_num: 14,
  //   enabled: true,
  // },
  // {
  //   id: 13,
  //   name: "AI视频站",
  //   icon: "/images/menu/video.png",
  //   url: "/video",
  //   sort_num: 15,
  //   enabled: true,
  // },
]);
const moreNavs = ref([]);
const curPath = ref(router.currentRoute.value.path);
const activePath = computed(() => {
  return router.currentRoute.value.meta?.activePath;
});
const isActive = (item) => {
  let path = normalizeUrl(item.path);
  return path === curPath.value || path === activePath.value;
};
const userName = computed((params) => {
  return userStore.getUser.roleList.map((d) => d.name).join(",");
});
// const requestDialogType = ref("");
const requestDialogRef = useTemplateRef("requestDialogRef");
const requestHandle = (type) => {
  requestDialogRef.value.open(type);
  // requestDialogType.value = type;
};
const dropDownVisibleChange = async (val) => {
  if (val) {
    let info = await getInfo();
    userStore.setUser(info);
  }
};
const requestDialogCallback = (params) => {};
function normalizeUrl(url) {
  if (url.startsWith("/")) {
    return url;
  }
  return "/" + url;
}
const title = ref("");
const mainWinHeight = window.innerHeight - 50 - 30;
const loginUser = ref({});
const version = ref(import.meta.env.VITE_APP_VERSION);
const routerViewKey = ref(0);
const showConfigDialog = ref(false);

const userInfo = (command) => {
  console.log("command :>> ", command);
};
const toolLogin = (params) => {
  window.open(`${import.meta.env.VITE_APP_ADMIN_URL}?accessToken=${getUserToken()}`);
  // window.open(`http://localhost:80/?accessToken=${getUserToken()}`);
};
const store = useSharedStore();
const show = ref(false);
watch(
  () => store.showLoginDialog,
  (newValue) => {
    show.value = newValue;
  }
);
window.document.documentElement.setAttribute("data-theme", userStore.theme);
const changeTheme = (val) => {
  userStore.setTheme(val);
  window.document.documentElement.setAttribute("data-theme", val);
};

// 监听路由变化
router.beforeEach((to, from, next) => {
  console.log(to);
  curPath.value = to.path;
  next();
});
if (curPath.value === "/external") {
  curPath.value = router.currentRoute.value.query.url;
}
const changeNav = (item) => {
  if (item.path.indexOf("http") !== -1) {
    // 外部链接
    // router.push({ name: "ExternalLink", query: { url: item.path } });
    window.open(item.path);
  } else {
    getUserToken() && (curPath.value = item.path);
    router.push(item.path);
  }
};

onMounted(() => {
  init();
});

const getUser = computed(() => {
  return getUserToken();
});
const init = async () => {};
const logout = async () => {
  await loginOut();
  removeUserToken();
  router.push("/");
};

const loginCallback = () => {
  init();
  // 刷新组件
  routerViewKey.value += 1;
};
const phone = ref();
const loginCatch = async (res, phoneNumber) => {
  if (res.code == 1002003010) {
    phone.value = phoneNumber;
    await ElMessageBox.confirm(res.msg, "提示");
    requestHandle();
  }
};
</script>

<style lang="stylus" scoped>
@import "../assets/css/custom-scroll.styl"
@import "../assets/css/home.styl"
:deep(.el-image__error){
  font-size:10px
  text-align: center
}
.home .navbar{
  .icon-yueliang{
    color:var(--switch-bg)
  }
  :deep(.el-switch__core){
    background-color: var(--switch-bg);
    border-color:var(--switch-border);
  }
}
</style>
